package com.dylon.seapiweb.controller;

import com.dylon.common.base.AjaxResult;
import com.dylon.common.utils.ServletUtils;
import com.dylon.common.utils.StringUtils;
import com.dylon.system.service.ISysMenuService;
import com.dylon.system.service.ISysUserService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登入验证
 */
@Log4j2
@Controller
public class LoginController extends BaseController {

    @Autowired
    ISysUserService sysUserService;
    @Autowired
    ISysMenuService sysMenuService;


    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(HttpServletRequest request, HttpServletResponse response){
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)){
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        return "login";
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult ajaxLogin(String account, String password, Boolean rememberMe){
        log.info("登入=======开始==============");
        System.out.println("登入=======开始==============");
        UsernamePasswordToken token = new UsernamePasswordToken(account, DigestUtils.md5Hex(password),rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try {
            log.info("登入======处理===============");
            System.out.println("登入=======处理==============");
            // 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
            // 每个Realm都能在必要时对提交的AuthenticationTokens作出反应
            // 所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
            subject.login(token);
            return success();
        }catch (AuthenticationException e){
            String msg = "账号或密码错误！";
            if(StringUtils.isNotEmpty(e.getMessage())){
                msg = e.getMessage();
            }
            log.error("登入======异常======="+ msg , e);
            System.out.println("登入=======异常=============="+ msg);
            return error(msg);
        }
    }

    @GetMapping("/unauth")
    public String unauth() { return "/error/unauth"; }
}
